package LinkedListSeries;

import java.util.HashSet;
import java.util.Set;

public class HasCycleSolution_hot100_141 {
    public boolean hasCycle(ListNode head) {
        // 判断链表中的环， 快慢指针
        if (head == null || head.next == null) {
            return false;
        }

        // 假想一个在 head 之前的虚拟节点
        // 慢指针从虚拟节点移动一步到达 head，快指针从虚拟节点移动两步到达 head.next
        // 否则无法使用while循环
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }

            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }

    public boolean hasCycle_2(ListNode head) {
        Set<ListNode> set = new HashSet<>();
        ListNode cur = head;
        while (cur != null) {
            boolean success = set.add(cur);
            if (!success) {
                return true;
            }
            cur = cur.next;
        }

        return false;
    }
}
